package com.atguigu.patterns.singleton;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class SingletonTest {

	public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
		AbstractSingleton instance, instance2;
		Class<AbstractSingleton>[] singletons = new Class[]{
				SingletonStaticVariable.class, // 饿汉模式-静态变量
				SingletonStaticCodeBlock.class, // 饿汉模式-静态代码块
				SingletonThreadNotSafe.class, // 懒汉模式-线程不安全
				SingletonSyncMethod.class, // 懒汉模式-同步方法
				SingletonSyncCodeBlock.class, // 懒汉模式-同步代码块
				SingletonDoubleCheck.class, // 双重验证
				SingletonStaticInnerClass.class, // 静态内部类
//				SingletonEnum.class // 枚举类
		};

		for (Class<AbstractSingleton> singleton : singletons) {
			Method getInstance = singleton.getDeclaredMethod("getInstance");
			instance = (AbstractSingleton) getInstance.invoke(null);
			instance2 = (AbstractSingleton) getInstance.invoke(null);
			sout(instance, instance2);
		}

		// 枚举类
		instance = SingletonEnum.INSTANCE;
		instance2 = SingletonEnum.INSTANCE;
		sout(instance, instance2);
		((SingletonEnum) instance).sayOK();
	}

	private static void sout(AbstractSingleton instance, AbstractSingleton instance2) {
		System.out.println(instance == instance2); // true
		System.out.println("instance.hashCode=" + instance.hashCode());
		System.out.println("instance2.hashCode=" + instance2.hashCode());
	}
}
